<template>
  <div class="encryption-test">
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <h2>🔐 端到端加密测试</h2>
          <el-tag :type="encryptionStore.isHealthy ? 'success' : 'danger'">
            {{ encryptionStore.isHealthy ? '加密服务正常' : '加密服务异常' }}
          </el-tag>
        </div>
      </template>

      <!-- 加密服务状态 -->
      <el-row :gutter="20" class="status-section">
        <el-col :span="8">
          <el-statistic title="加密服务状态" :value="encryptionStore.isAvailable ? '可用' : '不可用'" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="活跃任务" :value="encryptionStore.activeTaskCount" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="最近错误" :value="encryptionStore.recentErrors.length" />
        </el-col>
      </el-row>

      <el-divider />

      <!-- 团队选择 -->
      <div class="team-section">
        <h3>选择测试团队</h3>
        <el-select v-model="selectedTeamId" placeholder="请选择团队" @change="onTeamChange">
          <el-option
            v-for="team in testTeams"
            :key="team.id"
            :label="team.name"
            :value="team.id"
          />
        </el-select>
        
        <div v-if="selectedTeamId" class="team-key-info">
          <h4>团队密钥信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="密钥版本">{{ teamKeyInfo?.keyVersion || 'N/A' }}</el-descriptions-item>
            <el-descriptions-item label="算法">{{ teamKeyInfo?.algorithm || 'N/A' }}</el-descriptions-item>
            <el-descriptions-item label="密钥长度">{{ teamKeyInfo?.keyLength || 'N/A' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(teamKeyInfo?.status)">
                {{ teamKeyInfo?.status || 'N/A' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <div class="key-actions">
            <el-button @click="refreshTeamKey" :loading="keyLoading">刷新密钥</el-button>
            <el-button @click="rotateTeamKey" :loading="keyLoading" type="warning">轮换密钥</el-button>
            <el-button @click="checkKeyHealth" :loading="keyLoading" type="info">健康检查</el-button>
          </div>
        </div>
      </div>

      <el-divider />

      <!-- 加密测试 -->
      <div class="encryption-section">
        <h3>加密/解密测试</h3>
        
        <el-form :model="testForm" label-width="120px">
          <el-form-item label="测试内容">
            <el-input
              v-model="testForm.content"
              type="textarea"
              :rows="3"
              placeholder="请输入要加密的内容"
            />
          </el-form-item>
          
          <el-form-item label="文件名">
            <el-input
              v-model="testForm.fileName"
              placeholder="可选：测试文件名加密"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button @click="testEncryption" :loading="testLoading" type="primary">
              🔐 测试加密
            </el-button>
            <el-button @click="testDecryption" :loading="testLoading" :disabled="!encryptedData">
              🔓 测试解密
            </el-button>
            <el-button @click="clearTest" type="info">清空</el-button>
          </el-form-item>
        </el-form>

        <!-- 加密结果 -->
        <div v-if="encryptedData" class="result-section">
          <h4>加密结果</h4>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="密文">
              <el-input
                :value="encryptedData.ciphertext"
                readonly
                type="textarea"
                :rows="2"
              />
            </el-descriptions-item>
            <el-descriptions-item label="IV">{{ encryptedData.iv }}</el-descriptions-item>
            <el-descriptions-item label="算法">{{ encryptedData.algorithm }}</el-descriptions-item>
            <el-descriptions-item v-if="encryptedFileName" label="加密文件名">
              {{ encryptedFileName.ciphertext }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 解密结果 -->
        <div v-if="decryptedData" class="result-section">
          <h4>解密结果</h4>
          <el-alert
            :title="decryptedData.content === testForm.content ? '✅ 解密成功！内容一致' : '❌ 解密失败！内容不一致'"
            :type="decryptedData.content === testForm.content ? 'success' : 'error'"
            show-icon
          />
          <el-descriptions :column="1" border style="margin-top: 10px;">
            <el-descriptions-item label="解密内容">{{ decryptedData.content }}</el-descriptions-item>
            <el-descriptions-item v-if="decryptedData.fileName" label="解密文件名">
              {{ decryptedData.fileName }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <el-divider />

      <!-- 性能测试 -->
      <div class="performance-section">
        <h3>性能测试</h3>
        <el-button @click="runPerformanceTest" :loading="perfLoading" type="success">
          🚀 运行性能测试
        </el-button>
        
        <div v-if="performanceResult" class="performance-result">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="加密速度">{{ performanceResult.encryptionsPerSecond }} 次/秒</el-descriptions-item>
            <el-descriptions-item label="解密速度">{{ performanceResult.decryptionsPerSecond }} 次/秒</el-descriptions-item>
            <el-descriptions-item label="平均加密时间">{{ performanceResult.avgEncryptionTime.toFixed(2) }} ms</el-descriptions-item>
            <el-descriptions-item label="平均解密时间">{{ performanceResult.avgDecryptionTime.toFixed(2) }} ms</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 错误日志 -->
      <div v-if="encryptionStore.recentErrors.length > 0" class="error-section">
        <h3>最近错误</h3>
        <el-timeline>
          <el-timeline-item
            v-for="error in encryptionStore.recentErrors"
            :key="error.timestamp"
            :timestamp="new Date(error.timestamp).toLocaleString()"
            type="danger"
          >
            <strong>{{ error.name }}</strong>: {{ error.message }}
            <div v-if="error.teamId">团队ID: {{ error.teamId }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useEncryptionStore } from '@/stores/encryption'
import teamKeyApi, { type TeamKeyResponse } from '@/api/teamKey'
import { EncryptionUtils, type EncryptedMessage } from '@/utils/encryption'

// 状态管理
const encryptionStore = useEncryptionStore()

// 响应式数据
const selectedTeamId = ref<number>()
const teamKeyInfo = ref<TeamKeyResponse>()
const keyLoading = ref(false)
const testLoading = ref(false)
const perfLoading = ref(false)

// 测试表单
const testForm = reactive({
  content: '这是一条测试消息，用于验证端到端加密功能。🔐',
  fileName: 'test-file.txt'
})

// 测试结果
const encryptedData = ref<EncryptedMessage>()
const encryptedFileName = ref<EncryptedMessage>()
const decryptedData = ref<{ content: string; fileName?: string }>()
const performanceResult = ref<any>()

// 测试团队数据
const testTeams = ref([
  { id: 1, name: '测试团队 1' },
  { id: 2, name: '测试团队 2' },
  { id: 3, name: '测试团队 3' }
])

// 生命周期
onMounted(async () => {
  await encryptionStore.initialize()
})

// 方法
const onTeamChange = async () => {
  if (!selectedTeamId.value) return
  
  keyLoading.value = true
  try {
    teamKeyInfo.value = await teamKeyApi.getCurrentKey(selectedTeamId.value)
    ElMessage.success('团队密钥加载成功')
  } catch (error) {
    ElMessage.error('加载团队密钥失败: ' + (error as Error).message)
  } finally {
    keyLoading.value = false
  }
}

const refreshTeamKey = async () => {
  if (!selectedTeamId.value) return
  await onTeamChange()
}

const rotateTeamKey = async () => {
  if (!selectedTeamId.value) return
  
  keyLoading.value = true
  try {
    teamKeyInfo.value = await teamKeyApi.rotateKey(selectedTeamId.value)
    ElMessage.success('密钥轮换成功')
  } catch (error) {
    ElMessage.error('密钥轮换失败: ' + (error as Error).message)
  } finally {
    keyLoading.value = false
  }
}

const checkKeyHealth = async () => {
  if (!selectedTeamId.value) return
  
  keyLoading.value = true
  try {
    const health = await teamKeyApi.getKeyHealth(selectedTeamId.value)
    ElMessage({
      type: health.healthy ? 'success' : 'warning',
      message: health.message
    })
  } catch (error) {
    ElMessage.error('健康检查失败: ' + (error as Error).message)
  } finally {
    keyLoading.value = false
  }
}

const testEncryption = async () => {
  if (!selectedTeamId.value || !testForm.content) {
    ElMessage.warning('请选择团队并输入测试内容')
    return
  }
  
  testLoading.value = true
  try {
    // 加密内容
    encryptedData.value = await encryptionStore.encryptMessage(
      testForm.content,
      selectedTeamId.value
    )
    
    // 加密文件名（如果有）
    if (testForm.fileName) {
      encryptedFileName.value = await encryptionStore.encryptMessage(
        testForm.fileName,
        selectedTeamId.value
      )
    }
    
    ElMessage.success('加密测试成功')
  } catch (error) {
    ElMessage.error('加密测试失败: ' + (error as Error).message)
  } finally {
    testLoading.value = false
  }
}

const testDecryption = async () => {
  if (!selectedTeamId.value || !encryptedData.value) {
    ElMessage.warning('请先进行加密测试')
    return
  }
  
  testLoading.value = true
  try {
    const content = await encryptionStore.decryptMessage(
      encryptedData.value,
      selectedTeamId.value
    )
    
    let fileName: string | undefined
    if (encryptedFileName.value) {
      fileName = await encryptionStore.decryptMessage(
        encryptedFileName.value,
        selectedTeamId.value
      )
    }
    
    decryptedData.value = { content, fileName }
    ElMessage.success('解密测试成功')
  } catch (error) {
    ElMessage.error('解密测试失败: ' + (error as Error).message)
  } finally {
    testLoading.value = false
  }
}

const clearTest = () => {
  encryptedData.value = undefined
  encryptedFileName.value = undefined
  decryptedData.value = undefined
  ElMessage.info('测试数据已清空')
}

const runPerformanceTest = async () => {
  perfLoading.value = true
  try {
    performanceResult.value = await EncryptionUtils.benchmarkEncryption()
    ElMessage.success('性能测试完成')
  } catch (error) {
    ElMessage.error('性能测试失败: ' + (error as Error).message)
  } finally {
    perfLoading.value = false
  }
}

const getStatusType = (status?: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'expired': return 'danger'
    case 'revoked': return 'warning'
    default: return 'info'
  }
}
</script>

<style scoped lang="scss">
.encryption-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .test-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        color: var(--el-text-color-primary);
      }
    }
  }

  .status-section {
    margin-bottom: 20px;
  }

  .team-section {
    .team-key-info {
      margin-top: 20px;

      h4 {
        margin-bottom: 10px;
        color: var(--el-text-color-primary);
      }

      .key-actions {
        margin-top: 15px;
        display: flex;
        gap: 10px;
      }
    }
  }

  .encryption-section {
    .result-section {
      margin-top: 20px;

      h4 {
        margin-bottom: 10px;
        color: var(--el-text-color-primary);
      }
    }
  }

  .performance-section {
    .performance-result {
      margin-top: 15px;
    }
  }

  .error-section {
    margin-top: 20px;

    h3 {
      color: var(--el-color-danger);
    }
  }
}
</style>
